package com.silverhaze.diamond.client.ui.table.model;

import com.silverhaze.diamond.client.common.AuroraConstants;
import com.silverhaze.diamond.common.entity.SystemUser;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.ui.UIStringConstants;

import java.util.List;

/**
 * Author: Ivan Babanin
 * © Lizard Software, 2008 y.
 */
public class UsersTableModel extends AbstractServiceTableModel<SystemUser> {
    private List<SystemUser> dataList;
    private static final int colCount = 4;

    public UsersTableModel(List dataList) {
        super(dataList);
        this.dataList = dataList;
    }

    protected void createFields() {
        setColCountSize(colCount);
        setColumnName(new String[]{
                UIStringConstants.ID,
                UIStringConstants.LOGIN,
                UIStringConstants.RIGHTS,
                UIStringConstants.LAST_AUTH_DATE});
    }

    public void fillData(List data) {
        int i = 0;

        this.dataList = data;
        setData(new Object[data.size()][colCount]);

        for (Object o : data) {
            SystemUser u = (SystemUser) o;

            getData()[i][0] = u.getId();
            getData()[i][1] = u.getLogin();
            getData()[i][2] = u.isAdmin() ? UIStringConstants.ADMINISTRATOR : UIStringConstants.USER;
            getData()[i][3] = AuroraConstants.DATE_TIME_FORMAT.format(u.getLastLogin());
            i++;
        }

        setRowCountSize(i);
    }

    public SystemUser getObjectAtRow(int row) {
        assert row >= 0 && row < dataList.size() : "Row index is out of bounds: " + row + " > " + dataList.size();
        return dataList.get(row);
    }

    public void refreshModelAll() {
        fillData(DAOLocator.getInstance().getUsers());
        refreshModel();
    }
}
